import { removeToken } from './auth.js'
import router from '../router/index.js'
import {useUsersStore} from '../stores/user.js'
import {menuStore} from '../stores/menu.js'
import {uploadFileMinio} from "@/server/common/files.js"
/**
 * 获取uuid
 */
export function getUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}
// 前缀做代理拦截!
export const adornUrl = (actionName) => {
    return import.meta.env.VITE_APP_BASE_API + actionName
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth (key) {
    if(key) {
        return JSON.parse(sessionStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false
    }else{
        return true
    }
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

/**
 * 清除登录信息
 */
export function clearLoginInfo () {
  removeToken()
  useUsersStore().clearUserInfo()
  menuStore().clearMenu()
  router.options.isAddDynamicMenuRoutes = false
}

// 获取sessionStorage
export function getSession(sessionKey) {
  if(sessionKey) return JSON.parse(sessionStorage.getItem(sessionKey))
}
// 设置sessionStorage
export function setSession(sessionKey, val) {
  if(sessionKey) return sessionStorage.setItem(sessionKey, JSON.stringify(val))
}
// 删除sessionStorage
export function removeSession(sessionKey) {
  if(sessionKey) return sessionStorage.removeItem(sessionKey)
}
// 获取表单数据
export const paramsData = (formData=[]) => {
    return formData.reduce((obj,item) => {
        obj[item.key] = item.value
        return obj
    },{})
}
// 上传文件
const uploadFun = async(file) => {
    return new Promise((resolve, rejects) => {
        if(file?.type === 'string') {resolve(file.url)}
        else{
            let formData = new FormData()
            formData.append("file", file.raw)
            uploadFileMinio(formData).then(({data}) => {
                resolve(data.fileUrl)
            }).catch(msg => {
                rejects(msg)
            })
        }
    })
}
// 上传文件集合
export const waitFiles = async(fils) => {
    return new Promise(async(resolve, reject) => {
        let promiseList = [];
        (fils||[]).forEach(file => {
            promiseList.push(uploadFun(file))
        })
        let urls = await Promise.all(promiseList)
        resolve(urls)
        console.log(urls);
    })
}